# -*- coding: utf-8 -*-

import time

import ctypes
from random import random

from multiprocessing import (
    Process,
    Value,
    Queue,
)

import sys
import logging

logger = logging.getLogger(__name__)


def logger_config():
    logger_format = '%(asctime)s.%(msecs)03d %(processName)24s %(funcName)16s %(lineno)3d  %(message)s'
    logging.basicConfig(format=logger_format, datefmt='%H:%M:%S', level=logging.INFO, stream=sys.stdout)
    pass


class ExtendsProcess(Process):
    """继承进程"""

    def __init__(self, delay: float, **kwargs):
        super().__init__(**kwargs)
        self.delay = delay
        pass

    def run(self):
        logger.info('start')
        time.sleep(self.delay)
        logger.info('sleep:%f', self.delay)
        pass


def target_function(delay: float):
    """目标函数方式创建线程"""
    logger.info('start')
    time.sleep(delay)
    logger.info('sleep:%f', delay)

    pass


def create_process():
    """创建线程的两种方式"""

    # 实例化继承进程重写方式创建进程
    extends_process = ExtendsProcess(random(), name='ExtendsProcess')
    extends_process.start()
    extends_process.join()

    # 以目标函数作为参数创建进程
    process = Process(target=target_function, args=(random(),), name='Process')
    process.start()
    process.join()

    pass


def value_target():
    global v
    logger.info('value:%d', v.value, )


def value_process():
    """
    Process配合Value使用
    """

    # 全局变量（同一文件）
    global v
    v = Value(ctypes.c_int, 10)
    process = Process(target=value_target, args=(), name='ValueProcess')
    process.start()
    process.join()
    pass


def queue_target(q: Queue):
    if not q.full():
        q.put_nowait('hello')
        pass
    time.sleep(random())
    if not q.empty():
        logger.info('queue:%s', q.get_nowait(), )
        pass
    pass


def queue_process():
    """
    Process配合Queue使用
    """
    # 共享变量（作为参数）
    queue = Queue(maxsize=9)

    for i in range(9):
        process = Process(target=queue_target, args=(queue,), )
        process.start()
        pass

    pass


if __name__ == '__main__':
    logger_config()

    create_process()
    # value_process()
    # queue_process()

    # 实例化继承进程方式创建进程
    # extends_process = ExtendsProcess(random(), name='extends_process')
    # extends_process.start()
    # extends_process.join()

    # args_tuple = ('hello', 'world')
    # # # 以目标函数作为参数创建进程
    # process = Process(target=target_function, args=args_tuple)
    # process.start()
    # process.join()

    time.sleep(10)
    logger.info('main')

    pass
